<template>
  <div class="addgoods">
    <el-row :guttar="20">
      <el-col :span="12" :offset="6">
        <el-steps :active="active" finish-status="success" class="steps">
          <el-step title="商品基本信息" />
          <el-step title="添加库存信息" />
          <el-step title="添加关联" />
        </el-steps>
      </el-col>
    </el-row>

    <div v-show="active==0" class="goodsdetail">
      <el-card shadow="always" class="card">
        <el-form ref="form" :rules="rules" :model="form" label-width="80px">
          <el-row :guttar="20">
            <el-col :span="8">
              <el-form-item label="商品名称">
                <el-input v-model="form.gname" size="small" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="品牌">
                <el-select v-model="form.value" size="small" placeholder="品牌">
                  <el-option
                    v-for="item in brandList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.cname"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="原产地">
                <el-cascader
                  v-model="selectCitys"
                  size="small"
                  :options="cityOptions"
                  @change="handleChange"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :guttar="20">
            <el-col :span="8">
              <el-form-item label="商家编码">
                <el-input v-model="form.pcode" size="small" placeholder="商家自定义" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关键词">
                <el-input v-model="form.keyword" size="small" placeholder="不要用逗号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="商品描述">
                <el-input v-model="form.descr" size="small" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="封面图片">
                <el-upload
                  action="/api/leju/admin/material/uploadImg"
                  :on-success="onUploadSucc"
                  :file-list="fileList"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <img :src="form.cover_img" alt="">
            </el-col>
          </el-row>

          <el-row :guttar="20">
            <el-col :span="8">
              <el-form-item label="是否上架">
                <el-switch v-model="form.isshow" active-value="1" inactive-value="0" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否最热">
                <el-switch v-model="form.ishot" active-value="1" inactive-value="0" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="是否最新">
                <el-switch v-model="form.isnew" active-value="1" inactive-value="0">
                  <!-- <template slot-scope="scope">
                                        <span>{{ scope.row.isnew == false ? "0" : "1" }}</span>
                                    </template> -->
                </el-switch>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :guttar="20">
            <el-col :span="8">
              <el-form-item label="进价">
                <el-input-number v-model="form.price_in" size="small" :min="1" @change="handleChange" />
                <span>(单位：分)</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="售价">
                <el-input-number v-model="form.price_out" size="small" :min="1" @change="handleChange" />
                <span>(单位：分)</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="当前价格">
                <el-input-number v-model="form.price_now" size="small" :min="1" @change="handleChange" />
                <span>(单位：分)</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :guttar="20">
            <el-col :span="8">
              <el-form-item label="重量">
                <el-input-number v-model="form.weight" size="small" @change="handleChange" />
                <span>(单位：克)</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="排序">
                <el-input-number v-model="form.sort" size="small" :min="1" @change="handleChange" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位名称">
                <el-input v-model="form.unit_name" type="primary" size="small" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :guttar="20">
            <el-col :span="8">
              <el-form-item label="商品分类" size="small">
                <el-checkbox-group v-model="form.kindIds">
                  <el-checkbox v-for="item in kindList" :key="item.id" :label="item.id">{{ item.ctitle }}</el-checkbox>
                  <!-- <el-checkbox   label="创意">风格</el-checkbox>
                                    <el-checkbox   label="创意">装饰品</el-checkbox>
                                    <el-checkbox   label="创意">创意</el-checkbox> -->
                </el-checkbox-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="系列" size="small">
                <el-select v-model="form.seriesId" size="small">
                  <el-option
                    v-for="item in seriesAllList"
                    :key="item.id"
                    :label="item.cname"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="送货服务">
                <el-checkbox-group v-model="form.service_promise">
                  <el-checkbox :label="0">无</el-checkbox>
                  <el-checkbox :label="1">送货入户</el-checkbox>
                  <el-checkbox :label="2">上门安装</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>

        </el-form>
      </el-card>
      <div class="footerbutton">
        <el-button type="primary" size="small" @click="next">下一步,填写库存信息</el-button>
      </div>

    </div>

    <div v-show="active==1" class="skulist">
      <el-card class="skulist-main card">
        <el-form ref="skulistform" :model="form" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="详情标题">
                <el-input v-model="form.detail_title" type="primary" size="small" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="2">
              <el-form-item label="副标题">
                <el-input v-model="form.detail_desc" type="primary" size="small" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="添加sku">
                <span>颜色:</span>
                <el-checkbox-group v-model="colorlist">
                  <el-checkbox v-for="item in colorObjList" :key="item.value" :label="item.text">
                    <span :style="{color:item.value}"> {{ item.text }}</span>
                    <span style="font-size:14px" @click="delColorlist(item.text)">删除</span>
                  </el-checkbox>
                </el-checkbox-group>
                <div class="add-color-item">
                  <el-input v-model="colorObj.text" style="width:160px" type="primary" size="mini" placeholder="颜色描述:比如土豪金" />
                  <el-color-picker v-model="colorObj.value" class="color-picker" />
                  <el-button size="mini" type="primary" @click="addColorObj">创建sku选项</el-button>
                </div>

                <!-- 创建sku列表 -->
                <div>
                  <el-button type="primary" size="mini" @click="buildSkulist">生成sku列表</el-button>
                  <el-table
                    :data="skuList"
                    border
                    style="width: 100%"
                  >
                    <el-table-column

                      prop="color_text"
                      label="颜色"
                      width="150"
                    />
                    <el-table-column
                      prop="color"
                      label="色值"
                      width="120"
                    />
                    <el-table-column
                      prop="sku_code"
                      label="sku编码"
                      width="120"
                    />
                    <el-table-column
                      prop="price"
                      label="价格"
                      width="120"
                    />
                    <el-table-column
                      prop="count"
                      label="库存"
                      width="300"
                    />
                    <el-table-column
                      fixed="right"
                      label="操作"
                      width="100"
                    >
                      <template slot-scope="scope">
                        <el-button type="text" size="small" @click="removeSkulist(scope.row.tempId)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 轮播 -->
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="点击上传">
                <el-upload
                  action="/api/leju/admin/material/uploadImg"
                  :on-success="coverimgsSucc"
                  :file-list="fileList"
                >
                  <el-button size="small" type="primary">轮播图</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <img v-for="i in form.imgs" :key="i" :src="i" class="detail-img">
            </el-col>
          </el-row>

          <!-- 富文本选择器 -->
          <el-form-item label="商品详情">
            <TinymceEditor ref="tin" v-model="form.content" upload-url="http://bufantec.com/api/leju/admin/material/uploadImg">富文本</TinymceEditor>

            <!-- <el-button type="primary" size="default" @click = "getTin" >获取富文本内容</el-button>
                        <el-button type="primary" size="default" @click = "setTin">设置富文本内容</el-button> -->

          </el-form-item>
        </el-form>
      </el-card>
      <div class="footerbutton">
        <el-button type="primary" size="small" @click="backTofirst">返回上一步</el-button>
        <el-button type="primary" size="small" @click="next">下一步,填写关联商品</el-button>
      </div>

    </div>

    <div v-show="active==2" class="supply">
      <el-card shadow="always" class="card">
        <el-form ref="supplyform" :model="form" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="关联商品">
                <el-transfer v-model="linkProducts" :titles="['所有商品','选中商品']" :data="productList" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col>
              <el-form-item label="备注">
                <el-input v-model="form.bak" type="textarea" rows="2" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

      </el-card>

      <div class="footerbutton">
        <el-button type="primary" size="small" @click="backTosecond">返回上一步</el-button>
        <el-button type="primary" size="small" @click="saveGoods">保存</el-button>
      </div>

    </div>

  </div>
</template>

<script>
import _ from 'lodash'
import { brandList } from '@/api/brand'
import { seriesAllList } from '@/api/series'
import { kindList } from '@/api/kind'
import { productList, addProduct, productDetail, updateProduct } from '@/api/product'
import { regionDataPlus, CodeToText } from 'element-china-area-data'
import settingsFile from '@/settings'
import TinymceEditor from '@/components/Tinymce'
export default {
  components: {
    TinymceEditor
  },
  data() {
    return {
      Id: '', // 用于更新和编辑
      serveHost: settingsFile.host,
      selectCitys: [], // 对应的model 新增编辑完成后无需清空
      selectCityText: [], // 对应的省市区 新增和编辑
      city: [], // 城市编号 新增和编辑
      cityOptions: regionDataPlus,
      active: 0,
      form: {
        cover_img: '', // 图片
        imgs: [], // 轮播图片
        gname: '', // 商品名称
        value: '', // 品牌名称
        pcode: '', // 商品编码
        origin_code: '', // 城市编码
        origin_province: '', // 原产地省
        origin_city: '', // 原产地市
        origin_area: '', // 原产地区
        descr: '', // 商品描述
        keyword: '', // 关键词
        isshow: '1', // 是否上架
        ishot: '0', // 是否最热
        isnew: '0', // 是否最新
        price_in: '', // 进价
        price_out: '', // 售价
        price_now: '', // 当前价格
        unit_name: '', // 商品单位
        sort: '', // 排序
        seriesId: '', // 系列id
        kindIds: [], // 分类id
        service_promise: [], // 上门服务
        detail_title: '', // 详情标题
        detail_desc: '', // 副标题
        content: '', // 富文本内容
        link1: '', // 关联商品
        bak: ''// 备注
      },
      skuList: [], // 库存列表
      kindList: [], // 分类列表
      brandList: [], // 品牌列表
      seriesAllList: [], // 系列列表
      productList: [], // 商品列表
      linkProducts: [], // 关联商品
      page: {
        start: 1,
        limit: 10
      },
      fileList: [], // 图片上传
      colorlist: [], // 选中的颜色列表
      colorObj: {
        value: '', // 颜色
        text: '' // 输入框中的文字，最后被多选框选中(item.text)
      }, // 颜色集合
      colorObjList: [], // 新的颜色集合，需要在复选框中去循环
      rules: {
        gname: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, message: '长度至少一个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getBrandList()
    this.getSeriesAllList()
    this.getKindList()
    this.getProductList()
    this.getProductDetail() // 进入页面进行数据的更新
    // this.Id = this.$route.params.id;
    // console.log(this.id);
    console.log(this.$route.params.id)
  },
  methods: {
    // 点击编辑，根据id判断是否是新增或者编辑，如果有id传入，则为编辑，首先进行数据的更新
    getProductDetail() {
      if (this.$route.params.id) {
        this.Id = this.$route.params.id
        productDetail({
          id: this.Id
        }).then(res => {
          console.log('1111111111')
          console.log('11111', res)
          // 数据格式要符合表单
          var rs = res.data
          // 轮播图
          if (rs.imgs.indexOf(',') != -1) {
            // 分割成字符串数组,在编辑更新的时候使用join方法
            rs.imgs = rs.imgs.split(',')
          }
          // 商品分类
          if (rs.kindIds.indexOf(',') != -1) {
            rs.kindIds = rs.kindIds.split(',')
          }
          // 关联商品
          if (rs.link1.indexOf(',') != -1) {
            rs.link1 = rs.link1.split(',')
            this.linkProducts = rs.link1
          }
          // skulist
          this.skuList = rs.skuList
          // 省市区
          this.form.origin_province = rs.origin_province
          this.form.origin_city = rs.origin_city
          this.form.origin_area = rs.origin_area
          // 省市区编码

          // 修改过后将值赋值给form表单
          this.form = rs
          this.form.kindIds = rs.kindIds.join(',')
          this.form.link1 = this.linkProducts.join(',')
          // this.form.imgs = rs.imgs.join(",");
        })
      }
    },
    // 商品列表
    getProductList() {
      productList({
        start: this.page.start,
        limit: this.page.limit
        // pcode:this.page.pcode,
        // gname:this.page.gname
      }).then(res => {
        console.log(res)
        var list = res.data.list
        list.forEach(item => {
          this.productList.push({
            // 因为productList为Transfer的数据源，array[{ key, label, disabled }]
            // 需要使用key和label
            key: item.id,
            label: item.gname
          })
        })
      })
    },
    // 分类列表
    getKindList() {
      kindList().then(res => {
        console.log(res)
        this.kindList = res.data
      })
    },
    // 品牌列表
    getBrandList() {
      brandList({
        start: this.page.start,
        limit: this.page.limit
      }).then(res => {
        console.log(res)
        this.brandList = res.data.list
      })
    },
    // 系列列表
    getSeriesAllList() {
      seriesAllList().then(res => {
        console.log(res)
        this.seriesAllList = res.data
        console.log(this.seriesAllList)
      })
    },
    // 步骤条
    next() {
      if (++this.active > 2) this.active = 0
    },
    // 原产地省市区选择器
    handleChange(value) {
      if (value.length > 0) {
        // 城市编号value
        console.log(value)
        this.city.push(value)

        value.forEach(item => {
          this.selectCityText.push(CodeToText[item])
        })
      }
      // 城市编码
      this.form.origin_code = this.city.join(',')
      // 三级城市选择（省市区）
      console.log(this.selectCityText)
      this.form.origin_province = this.selectCityText[0]
      this.form.origin_city = this.selectCityText[1]
      this.form.origin_area = this.selectCityText[2]
      // console.log(this.form.origin_province);
    },
    // 创建sku选项
    addColorObj() {
      var colorNewobj = _.clone(this.colorObj)
      this.colorObjList.push(colorNewobj)
      console.log(this.colorObjList)
      this.colorObj = {}
    },
    // 删除sku选项
    delColorlist(text) {
      this.colorObjList = this.colorObjList.filter(item => item.text != text)
    },
    // 创建sku列表
    buildSkulist() {
      []
      this.colorObjList.forEach(item => {
        this.skuList.push({
          tempId: item.text,
          color: item.value,
          color_text: item.text,
          count: 0,
          price: 0,
          sku_code: ''
        })
      })
    },
    // 删除sku列表
    removeSkulist(tempId) {
      this.skuList = this.skuList.filter(item => item.tempId != tempId)
    },
    // 图片上传成功后的回调
    onUploadSucc(response, file, fileList) {
      console.log(response)
      this.form.cover_img = response.ossUrl
      this.$message.success('上传成功')
    },
    // 轮播图成功的回调
    coverimgsSucc(response, file, fileList) {
      console.log(response)
      this.form.imgs.push(response.ossUrl)
      console.log('22222', this.form.imgs)
      this.$message.success('上传成功')
    },
    // 获取富文本
    getTin() {
      var rs = this.$refs.tin.getContent()
      return rs
    },
    // 设置富文本
    setTin(v) {
      this.$refs.tin.setContent(v)
    },

    backTofirst() {
      this.active--
    },
    backTosecond() {
      this.active--
    },
    // 保存商品
    saveGoods() {
      if (!this.Id) {
        addProduct({
          ...this.form
        }).then(res => {
          console.log(res)
          this.$message.success('新增成功')
          this.$router.push({ name: productList, path: '/product/list' })
          this.getProductList()
        })
      } else {
        updateProduct({
          id: this.Id,
          ...this.form
        }).then(res => {
          console.log(res)
          this.$message.success('修改成功')
          this.$router.push({ name: productList, path: '/product/list' })
          this.getProductList()
        })
      }
    }

  }
}
</script>

<style lang="scss" scoped>
    .addgoods {
        .steps{
            margin:20px;
            width:600px;
        }
        .goodsdetail{
            .card{
                margin:30px 100px;
            }
            img{
                width:120px;
                // height: 120px;
            }
        }
        .footerbutton{
           width:300px;
           height: 30px;
           margin:10px auto;
        }
        .skulist{
            .card{
                margin:30px 100px;
            }
        }
        .add-color-item{
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .color-picker{
                margin: 0 50px;
            }
        }
        .detail-img{
        width: 120px;
        // height: 120px;
    }
    }
</style>
